package com.example.myactspringboot.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

/**
 * @Author Zhouchb
 * @Create 2024-04-24 21:46
 * @Description
 */
@Configuration
public class KaptchaConfig {
    private static ResourceLoader resourceLoader = new DefaultResourceLoader();
    @Bean
    public DefaultKaptcha captchaGenerator() {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        Properties prop = loadProperties("classpath:/application.properties");
        Iterator<Object> iterator = prop.keySet().iterator();
        String key;
        String temp;
        while (iterator.hasNext()) {
            key = String.valueOf(iterator.next());
            temp = String.valueOf(prop.get(key));
            if (key.startsWith("kaptcha")) {
                properties.setProperty(key, temp);
            }
        }
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }

    private Properties loadProperties(String location) {
        Properties props = new Properties();
        InputStream is = null;
        try {
            Resource resource = resourceLoader.getResource(location);
            is = resource.getInputStream();
            props.load(is);
        } catch (IOException var12) {
            System.out.println(var12.getMessage());
        } finally {
            IOUtils.closeQuietly(is);
        }
        return props;
    }
}
